package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.GreenImageScan;
import com.heima.aliyun.GreenTextScan;
import com.heima.common.constants.mq.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.sun.xml.bind.v2.TODO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Resource
    WmNewsMapper wmNewsMapper;
    @Resource
    AdminFeign adminFeign;
    @Value("${file.oss.web-site}")
    String webSite;
    @Autowired
    GreenTextScan greenTextScan;
    @Autowired
    GreenImageScan greenImageScan;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void autoScanWmNews(Integer newsId) {
//        1.检查参数
        if (newsId == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
//        2.检查News状态
        WmNews wmNews = wmNewsMapper.selectById(newsId);
        if (wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到对应News");
        }
        if (!WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(wmNews.getStatus())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"News不是待审核状态");
        }
//        3.审核News
        String content = wmNews.getContent();
        List<Map> contentLists = JSON.parseArray(content, Map.class);
//          3.1 解析文本内容
        StringBuilder stringBuilder = new StringBuilder(wmNews.getTitle()+"_break_");
        contentLists.stream()
                .filter(o->WemediaConstants.WM_NEWS_TYPE_TEXT.equals(o.get("type")))
                .map(o->o.get("value").toString())
                .forEach(o-> stringBuilder.append(o).append("_break_"));
//          3.2 本地敏感词初审
        List<String> wordList = adminFeign.findAll().getData();
        SensitiveWordUtil.initMap(wordList);
        Map<String, Integer> matchWords = SensitiveWordUtil.matchWords(stringBuilder.toString());
        if (matchWords.size()>0){
            updateNews(wmNews,WemediaConstants.WM_NEWS_FAIL_STATUS,"文中有自定义敏感词");
            return;
        }
//          3.3 解析图片内容
        List<String> contentImages = contentLists.stream()
                .filter(o -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(o.get("type")))
                .map(o -> o.get("value").toString())
                .collect(Collectors.toList());
        if (StringUtils.isNotBlank(wmNews.getImages())){
            String[] split = wmNews.getImages().split(",");
            List<String> coverImages = Arrays.stream(split)
                    .map(o -> webSite + o)
                    .collect(Collectors.toList());
            contentImages.addAll(coverImages);
        }
        List<String> images = contentImages.stream().distinct().collect(Collectors.toList());

//          3.4 云审核文本 与 图片
        Boolean textResult = autoScanText(stringBuilder.toString(),wmNews);
        if (WemediaConstants.WM_NEWS_FAIL_STATUS.equals(wmNews.getStatus())){
            wmNewsMapper.updateById(wmNews);
            return;
        }
        log.info("图片列表{},大小{}",images,images.size());
        Boolean imageResult = autoScanImage(images,wmNews);
        if (textResult && imageResult){
            updateNews(wmNews,WemediaConstants.WM_NEWS_AUTHED_STATUS,null);
            long publishTime = wmNews.getPublishTime().getTime();
            long currentTime = System.currentTimeMillis();
            long time = publishTime-currentTime;
            rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                    , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                    , wmNews.getId()
                    , new MessagePostProcessor() {
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {
                            message.getMessageProperties().setHeader("x-delay",time>0 ? time:0);
                            return message;
                        }
                    });
            return;
        }
        wmNewsMapper.updateById(wmNews);

    }

    private Boolean autoScanImage(List<String> images, WmNews wmNews) {
        boolean flag = true;
        try {
            if (images == null || images.size() == 0){
                return flag;
            }
            Map map = greenImageScan.imageUrlScan(images);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case WemediaConstants.WM_PASS:
                    break;
                case WemediaConstants.WM_REVIEW:
                    wmNews.setStatus(WemediaConstants.WM_NEWS_MANUAL_STATUS);
                    flag = false;
                    break;
                case WemediaConstants.WM_BLOCK:
                    wmNews.setStatus(WemediaConstants.WM_NEWS_FAIL_STATUS);
                    wmNews.setReason("图中有违规内容");
                    flag = false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    private Boolean autoScanText(String text,WmNews wmNews) {
        boolean flag = true;
        try {
            Map map = greenTextScan.greenTextScan(text);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case WemediaConstants.WM_PASS:
                    break;
                case WemediaConstants.WM_REVIEW:
                    wmNews.setStatus(WemediaConstants.WM_NEWS_MANUAL_STATUS);
                    flag = false;
                    break;
                case WemediaConstants.WM_BLOCK:
                    wmNews.setStatus(WemediaConstants.WM_NEWS_FAIL_STATUS);
                    wmNews.setReason("文中有违规内容");
                    flag = false;
                    break;
            }

        } catch (Exception e) {
            e.printStackTrace();
            wmNews.setStatus(WemediaConstants.WM_NEWS_MANUAL_STATUS);
            flag = false;
        }
        return flag;
    }

    private void updateNews(WmNews wmNews, Short status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        wmNewsMapper.updateById(wmNews);
    }
}
